package com.kaka.bus.engine;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;

import com.google.gson.Gson;
import com.kaka.bus.AppCenter;
import com.kaka.bus.R;
import com.kaka.bus.api.Api;
import com.kaka.bus.base.MessageActivity;
import com.kaka.bus.bean.HttpWrapper;
import com.kaka.bus.bean.Lianxi;
import com.kaka.bus.bean.Status;
import com.kaka.bus.bean.UserInfo;
import com.kaka.bus.constant.Constant;
import com.kaka.bus.engine.borrow.bank.BankCardActivity;
import com.kaka.bus.engine.borrow.face.FaceActivity;
import com.kaka.bus.engine.borrow.idcard.IdCardBackActivity;
import com.kaka.bus.engine.borrow.idcard.IdCardFrontActivity;
import com.kaka.bus.engine.borrow.pact.PactActivity;
import com.kaka.bus.engine.borrow.person.PersonActivity;
import com.kaka.bus.engine.borrow.phone.PhoneActivity;
import com.kaka.bus.engine.borrow.signed.SignedActivity;
import com.kaka.bus.engine.borrow.zhima.ZhiMaActivity;
import com.kaka.bus.engine.other.DrainageActivity;
import com.kaka.bus.listener.Listener;
import com.kaka.bus.listener.RouterDisDialogListener;
import com.kaka.bus.manager.Result;
import com.kaka.bus.manager.T;
import com.kaka.bus.util.ToastUtil;
import com.kaka.bus.util.U;
import com.kaka.bus.util.UserUtil;
import com.kaka.bus.util.logger.Logger;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.HashSet;

import io.reactivex.disposables.CompositeDisposable;

/**
 * Created by zhangqi on 2017/6/9.
 *
 * 流程导航
 */

public class RouterUtil {

    private static Activity mActivity;
    private RouterUtil(){

    }

    public static void router(Activity activity, Api api, CompositeDisposable compositeDisposable, RouterDisDialogListener listener){
        UserInfo userInfo = UserUtil.getCache(UserUtil.USERINFO);
        String userId = userInfo.getId();
        compositeDisposable.add(api.checkNode(userId,U.Sign(userId))
                .compose(T.D())
                .subscribeWith(new Result<HttpWrapper<Status>>() {
                    @Override
                    protected void onSuccess(HttpWrapper<Status> wrapper) {
                        Logger.i("服务器给的code"+wrapper.code);
                        if(Constant.NODE_OK.equals(wrapper.code)){
                            bpmFinish(activity,api,compositeDisposable,listener);
                        }else if (Constant.NODE_NO.equals(wrapper.code)) {
                            Logger.i("未创建:" + wrapper.data);
                            /**
                             * 未认证状态 可能已经创建节点
                             */
                            listener.dissmiss();
                            if ("r".equals(wrapper.data)) {
                                U.toDrainage(activity, DrainageActivity.TYPE_REFUSE,Constant.REFUES);
                            } else if("4".equals(wrapper.data)){
                                RxPermissions rxPermissions = new RxPermissions(activity);
                                rxPermissions.request(Manifest.permission.READ_CONTACTS, Manifest.permission.READ_PHONE_STATE)
                                        .subscribe(aBoolean -> {
                                            if (aBoolean) {
                                                commitLocalContact("209", activity, api, compositeDisposable, listener);
                                            } else {
                                                listener.dissmiss();
                                                U.getSingleDialog(activity, "温馨提示", "您已经拒绝了权限,请在设置-应用管理中打开读取通讯录权限", "了解", null).show();
                                            }
                                        });
                            }else{
                                continues(activity,wrapper.data.getCodes());
                            }

                        }else if (Constant.ERROR_CODE.equals(wrapper.code)) {
                            ToastUtil.showShort(activity, "系统异常");
                            listener.dissmiss();
                        }else{
                            ToastUtil.showShort(activity,"系统异常");
                            listener.dissmiss();
                        }
                    }

                    @Override
                    protected void onFinish() {
                        listener.dissmiss();
                    }
                }));

    }

    private static void bpmFinish(Activity activity,Api api, CompositeDisposable compositeDisposable, RouterDisDialogListener listener) {
        UserInfo userInfo = UserUtil.getCache(UserUtil.USERINFO);
        String token = userInfo.getTokenId();
        String userId = userInfo.getId();
        compositeDisposable.add(api.NodeOk(userId,token,U.Sign(userId,token))
                .compose(T.D())
                .subscribeWith(new Result<HttpWrapper<String>>() {
                    @Override
                    protected void onSuccess(HttpWrapper<String> data) {

                        if(Constant.SUCCESS_CODE.equals(data.getCode())){
                            activity.startActivity(new Intent(activity, PactActivity.class));
                            activity.finish();
                        }else if(Constant.TOKEN_TIMEOUT.equals(data.code)){
                            U.tokenOut(activity);
                        }else if(Constant.ID_CODE.equals(data.code)){
                            activity.startActivity(new Intent(activity, HomeActivity.class));
                            activity.finish();
                        }
                    }

                    @Override
                    protected void onFinish() {
                        super.onFinish();
                        listener.dissmiss();
                    }
                }));
    }

    /**
     * 引导
     * @param activity
     * @param data
     */
    private static void continues(Activity activity,String data) {
        Class clazz = null;
        switch (data) {
            case "0":
                clazz = SignedActivity.class;
                break;
            case "1":
                clazz = IdCardFrontActivity.class;
                break;
            case "2":
                clazz = IdCardBackActivity.class;
                break;
            case "3":
                clazz = ZhiMaActivity.class;
                break;
            case "5":
                clazz = PersonActivity.class;
                break;
            case "6":
                clazz = FaceActivity.class;
                break;
            case "7":
                clazz = PhoneActivity.class;
                break;
            case "8":
                clazz = BankCardActivity.class;
                break;
            case "9":
                ToastUtil.showShort(activity,"系统异常");
                break;
        }
        activity.startActivity(new Intent(activity, clazz));
        activity.finish();
        activity.overridePendingTransition(R.anim.tran_in,R.anim.tran_out);
    }

    private static void commitLocalContact(String code, Activity activity, Api api, CompositeDisposable compositeDisposable, RouterDisDialogListener listener) {
        new Thread() {
            @Override
            public void run() {
                HashSet<Lianxi> allContactInfo = U.queryContacts(activity);

                if(allContactInfo.size() == 0){
                    activity.runOnUiThread(() -> {
                        listener.dissmiss();
                        U.getSlectDialog(activity, "提示", "通讯录为空读取通讯录权限可能被拒绝,请先开启权限", "取消", "前去设置",
                                new Listener.OnNormalAlertDialogChooseClickListener() {
                                    @Override
                                    public void onLeft() {

                                    }

                                    @Override
                                    public void onRight() {
                                        Intent intent = new Intent();
                                        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                        Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
                                        intent.setData(uri);
                                        activity.startActivity(intent);
                                    }
                                }).show();
                    });
                    return;
                }

                String json = new Gson().toJson(allContactInfo);
                Logger.i("联系人提交的信息"+allContactInfo.size() + "---" + json);
                String userInfo = AppCenter.mSpUtil.getString(Constant.USERINFO, null);
                UserInfo userInfo1 = AppCenter.mGson.fromJson(userInfo, UserInfo.class);
                String userId = userInfo1.getId();
                if(activity instanceof MessageActivity){
                    activity.runOnUiThread(() -> {
                        MessageActivity msg = (MessageActivity)activity;
                        msg.showDialog("验证信息中..");
                    });

                }
                compositeDisposable.add(api
                        .commitContact(userId, json)
                        .compose(T.D())
                        .subscribeWith(new Result<HttpWrapper<String>>() {
                            @Override
                            protected void onSuccess(HttpWrapper<String> bean) {
                                if (Constant.SUCCESS_CODE.equals(bean.code)) {
                                    if("209".equals(code) || "210".equals(code)){
                                        /**
                                         * checkbpm
                                         */
                                        RouterUtil.router(activity,api ,compositeDisposable, () -> {
                                            listener.dissmiss();
                                        });
                                    }
                                } else if("207".equals(bean.code)){
                                    U.toDrainage(activity,DrainageActivity.TYPE_REFUSE,Constant.REFUES);
                                }else{
                                    commitcommitContactFaild(code,activity,api,compositeDisposable,listener);
                                }
                            }

                            @Override
                            protected void onFinish() {
                                listener.dissmiss();
                            }

                            @Override
                            public void onError(Throwable t) {
                                super.onError(t);
                                commitcommitContactFaild(code,activity,api,compositeDisposable,listener);
                            }
                        }));
            }
        }.start();
    }

    private static void commitcommitContactFaild(String code, Activity activity,Api api, CompositeDisposable compositeDisposable, RouterDisDialogListener listener) {
        U.getSlectDialog(activity, "温馨提示", "信息获取有误,请重新尝试", "取消", "重试一次", new Listener.OnNormalAlertDialogChooseClickListener() {
            @Override
            public void onLeft() {

            }

            @Override
            public void onRight() {
                commitLocalContact(code,activity,api,compositeDisposable,listener);
            }
        }).show();
    }
}
